<?php

namespace app\admin\service;

use app\model\Article;
use app\model\Book;
use app\model\Chapter;
use think\Exception;
use think\facade\App;

class sitemap
{
    protected $url = ""; //主站引子站
    protected $map_dir = "";
    protected $end_point;

    public function __construct($url = "", $map_dir = "")
    {
        $this->url = $url;
        $this->map_dir = $map_dir;

        $this->end_point = config('seo.book_end_point');

        require_once public_path() . "/routeconf.php";

    }

    public function gen($pagesize, $part, $end)
    {
        if ($end == 'pc') {
            $site_name = config('site.domain');
        } elseif ($end == 'm') {
            $site_name = config('site.mobile_domain');
        } elseif ($end == 'mip') {
            $site_name = config('site.mip_domain');
        }

        if ($part == 'book') {
            $this->genbook($pagesize, $site_name, $end);
        } elseif ($part == 'chapter') {
            $this->genchapter($pagesize, $site_name, $end);
        } elseif ($part == 'article') {
            $this->genarticle($pagesize, $site_name, $end);
        }
    }

    private function genbook($pagesize, $site_name, $end)
    {
        $data = Book::where('1=1');
        $total = $data->count();
        $page = intval(ceil($total / $pagesize));
        $urls = [];
        $master = $this->map_dir;
        $dir = App::getRootPath() . 'public' . $master;
        $this->mkdir_chmod($dir);

        $urlList = "";
        for ($i = 1; $i <= $page; $i++) {
            if ($i == 1) {
                $urlList .= '<a href="/sitemap.html">第' . ($i) . '页</a>';
            } else {
                $urlList .= '<a href="/sitemap_' . ($i) . '.html">第' . ($i) . '页</a>';
            }
        }
        for ($i = 1; $i <= $page; $i++) {
            $arr = array();
            $content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
            $books = $data->limit($pagesize * ($i - 1), $pagesize)->select();

            foreach ($books as &$book) {

                if ($this->end_point == 'id') {
                    $book['param'] = $book['id'];
                } else {
                    $book['param'] = $book['unique_id'];
                }

                if (is_numeric($book['create_time'])) {
                    $lastmod = date("Y-m-d", $book['create_time']);
                } else {
                    $lastmod = date("Y-m-d", strtotime($book['create_time']));
                }

                $temp = array(
                    'title' => $book['book_name'],
                    'loc' => $this->url . $site_name . '/' . BOOKCTRL . '/' . $book['param'],
                    'lastmod' => $lastmod,
                    'priority' => '1.0',
                );

                array_push($arr, $temp);
            }
            $this->generateHtml($arr, $i, $urlList, $page);
            foreach ($arr as $item) {
                $content .= $this->create_item($item);
            }
            $content .= '</urlset>';


            $sitemap_name = '/sitemap_book_' . $end . '_' . 'books' . '_' . $i . '.xml';
            array_push($urls, $site_name . $master . $sitemap_name);
            file_put_contents($dir . $sitemap_name, $content);
            if ($page == $i) {
                array_push($urls, $site_name . $master . '/sitemap_book_' . $end . '_newest' . '.xml');
                file_put_contents($dir . '/sitemap_book_' . $end . '_newest' . '.xml', $content);
            }
            echo '<a href="' . $site_name . $master . $sitemap_name . '" target="_blank">' . $end . '端网站地图制作成功！点击这里查看</a><br />';
            try {
                flush();
                ob_flush();
            } catch (\Throwable $e) {
            }

            unset($arr);
            unset($content);
        }
        file_put_contents($dir . "/sitemap_book_urls.txt", implode(PHP_EOL, $urls));
    }

    function mkdir_chmod($path, $mode = 0777)
    {
        if (is_dir($path)) {
            return true;
        }
        $result = mkdir($path, $mode, true);
        if ($result) {
            $path_arr = explode('/', $path);
            $path_str = '';
            foreach ($path_arr as $val) {
                $path_str .= $val . '/';
                chmod($path_str, $mode);
            }
        }
        return $result;
    }

    public function generateHtml($data, $tag = "", $urlList = "", $total = 1)
    {
        $content = file_get_contents(public_path() . "/sitemap_back.html");

        $html = "";
        foreach ($data as $value) {
            $url = $value['loc'];
            $html .= '<li class="aurl"><a href="' . $url . '" data-lastfrom="" title="' . $value['title'] . '">' . $value['title'] . '</a></li>';
        }
        $content = str_replace('##$urls##', $html, $content);
        $content = str_replace('##$page##', $tag, $content);
        $content = str_replace('##$total##', $total, $content);
        $content = str_replace('##$urlList##', $urlList, $content);
        if ($tag == 1) {
            file_put_contents(public_path() . "/sitemap.html", $content);
        } else {
            file_put_contents(public_path() . "/sitemap_{$tag}.html", $content);
        }
    }

    private function create_item($data)
    {
        $item = "<url>\n";
        $item .= "<loc>" . $data['loc'] . "</loc>\n";
        $item .= "<lastmod>" . $data['lastmod'] . "</lastmod>\n";
        $item .= "<priority>" . $data['priority'] . "</priority>\n";
        $item .= "</url>\n";
        return $item;
    }

    private function genchapter($pagesize, $site_name, $end)
    {

        $data = Chapter::where('1=1');
        $total = $data->count();
        $page = intval(ceil($total / $pagesize));
        $urls = [];
        $master = $this->map_dir;
        $dir = App::getRootPath() . 'public' . $master;
        $this->mkdir_chmod($dir);
        for ($i = 1; $i <= $page; $i++) {
            $arr = array();
            $content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
            $chapters = $data->limit($pagesize * ($i - 1), $pagesize)->select();
            foreach ($chapters as $chapter) {
                if (is_numeric($chapter['create_time'])) {
                    $lastmod = date("Y-m-d", $chapter['create_time']);
                } else {
                    $lastmod = date("Y-m-d", strtotime($chapter['create_time']));
                }
                $temp = array(
                    'title' => $chapter['chapter_name'] ?? '',
                    'loc' => $this->url . $site_name . '/' . CHAPTERCTRL . '/' . $chapter['id'],
                    'lastmod' => $lastmod,
                    'priority' => '1.0',
                );
                array_push($arr, $temp);
            }
            foreach ($arr as $item) {
                $content .= $this->create_item($item);
            }
            $content .= '</urlset>';


            $sitemap_name = '/sitemap_chapter_' . $end . '_' . 'chapters' . '_' . $i . '.xml';

            file_put_contents($dir . $sitemap_name, $content);
            array_push($urls, $site_name . $master . $sitemap_name);
            if ($i == $page) {
                file_put_contents($dir . '/sitemap_chapter_' . $end . '_newest' . '.xml', $content);
                array_push($urls, $site_name . $master . '/sitemap_chapter_' . $end . '_newest' . '.xml');
            }
            echo '<a href="' . $site_name . $master . $sitemap_name . '" target="_blank">' . $end . '端网站地图制作成功！点击这里查看</a><br />';
//            try {
//                flush();
//                ob_flush();
//            } catch (\Throwable $e) {
//            }
            unset($arr);
            unset($content);

        }
        file_put_contents($dir . "/sitemap_chapter_urls.txt", implode(PHP_EOL, $urls));
    }

    private function genarticle($pagesize, $site_name, $end)
    {
        $data = Article::where('1=1');
        $total = $data->count();
        $page = intval(ceil($total / $pagesize));
        for ($i = 1; $i <= $page; $i++) {
            $arr = array();
            $content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset>\n";
            $articles = $data->limit($pagesize * ($i - 1), $pagesize)->select();
            foreach ($articles as $article) {
                if ($this->end_point == 'id') {
                    $article['param'] = $article['id'];
                } else {
                    $article['param'] = $article['unique_id'];
                }
                $temp = array(
                    'loc' => $site_name . '/' . CHAPTERCTRL . '/' . $article['param'],
                    'priority' => '0.9',
                );
                array_push($arr, $temp);
            }
            foreach ($arr as $item) {
                $content .= $this->create_item($item);
            }
            $content .= '</urlset>';
            $sitemap_name = '/sitemap_article_' . $end . '_' . $i . '.xml';
            file_put_contents(App::getRootPath() . 'public' . $sitemap_name, $content);
            file_put_contents(App::getRootPath() . 'public' . '/sitemap_article_' . $end . '_newest' . '.xml', $content);
            echo '<a href="' . $sitemap_name . '" target="_blank">' . $end . '端网站地图制作成功！点击这里查看</a><br />';
            flush();
            ob_flush();
            unset($arr);
            unset($content);
        }
    }
}